//
//  HDIndividualCenterViewController.swift
//  HuaDaoPeifu
//
//  Created by Erickson on 16/3/28.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD

struct IndividualCenterModel {
    var icon : UIImage?
    var title : String?
}

class HDIndividualCenterViewController: UIViewController ,backPassImageDelegate{
    var header = HDIndividualTopView()
//    let header = HDCenterTableHeader(frame: CGRect(x: 0, y: 0, width: AppConstant.screenWidth, height: 205*(AppConstant.screenWidth/375)))
    let netJudge = PYPReachability()
    var indeviduals = [IndividualCenterModel]()
    var headImage = UIImageView()
    var alertInfo :HDProgressAlert?
    var data: Data?
    var image: UIImage?
    var integralLabel: UILabel?
    var integralCount : Int?
    
    @IBOutlet weak var centerTableView: UITableView!
    
    var userModel:HDAccountInfo?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        navigationController?.setNavigationBarHidden(true, animated: animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "个人中心"
        self.automaticallyAdjustsScrollViewInsets = false
        setupNotification()
        setupViews()
        setUpHeadImageView()
        setupModel()
    }
    
    /// 加载用户相关
    func loadUserData() {
        loadUserDetailInfo()
        loadHeadImage()
        loadIntegralCount()
    }
    
    /// 加载用户信息
    func loadUserDetailInfo() {
        HDApiManagerHandler.requestUserSettingInfo { (accountInfo:HDAccountInfo?) in
            self.userModel = accountInfo;
        }
    }
    
    /// 加载积分信息
    func loadIntegralCount(){
        if HDAccountHandler.loginType != .notLogin {
            HDApiManagerHandler.requestUserIntegral { (count:Int?) in
                guard let count = count else {
                    return
                }
                if count >= 0{
                    self.integralCount = count
                    self.centerTableView.reloadData()
                }
            }
        }
    }
    
    /// 加载用户头像
    func loadHeadImage(){
        // 去沙盒获取头像，设置头像
        self.header.userHeadImageView.image = HDAccountHandler.loadImage().headerImage
        // 异步请求网络头像
        SVProgressHUD.showDisableLoading(nil)
        HDApiManagerHandler.requestUserInfo { (accountInfo:HDAccountInfo?) in
            guard let accountInfo = accountInfo,
                let headimg = accountInfo.headimg,
                let usertype = accountInfo.user_type,
                let name = accountInfo.name else {
                    SVProgressHUD.dismiss()
                    return
            }
            // 处理usertype
            HDAccountHandler.saveUserIntType(Int(usertype)!)
            // 处理name
            HDAccountHandler.saveUserName(name)
            self.header.nameLabel.text = name
            
            // 处理头像
            
            if headimg.lengthOfBytes(using: String.Encoding.utf8) > 0 {
                DispatchQueue.global().async(execute: {
                    let data = try! Data.init(contentsOf: URL(string: headimg)!, options: Data.ReadingOptions(rawValue: 0))
                    let image = UIImage(data: data)
                    HDAccountHandler.saveUserHeadImage(image!)
                    DispatchQueue.main.async {
                        self.header.userHeadImageView.image = image
                        SVProgressHUD.dismiss()
                    }
                })
            }else{
                self.image = HDAccountHandler.userHeadImage
                self.header.userHeadImageView.image = self.image
                SVProgressHUD.dismiss()
            }
        }
    }
    
    func backPassImage(_ img: UIImage) {
        self.headImage.image = img
    }
    
    
    func setupNotification() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(HDIndividualCenterViewController.userLogin), name: NSNotification.Name(rawValue: HDUserNotification.userlogin), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(HDIndividualCenterViewController.userSignOut), name: NSNotification.Name(rawValue: HDUserNotification.userSignOut), object: nil)
        
        // 修改头像成功的通知
        NotificationCenter.default.addObserver(self, selector: #selector(resetHeadImage), name: NSNotification.Name?.init(NSNotification.Name(rawValue: HDUserNotification.resetHeadImage)), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 重新加载头像
    func resetHeadImage() {
        self.header.userHeadImageView.image = HDAccountHandler.loadImage().headerImage
    }
    
    func userLogin() {
        setupModel()
        updateUI()
        loadUserData()
        centerTableView.reloadData()
    }
    
    func userSignOut() {
        headImage.image = UIImage(named: "个人中心默认头像")
//        header.nameLabel.setTitle("注册/登录", for: UIControlState())
        setupModel()
        updateUI()
        
        centerTableView.reloadData()
    }
    
    func setupModel() {
        
        if HDAccountHandler.loginType == .notLogin {
            let individualModel1 = IndividualCenterModel(icon: UIImage(named: "fenxiangruanjian"), title: "分享软件")
            let individualModel2 = IndividualCenterModel(icon: UIImage(named: "jianyifankui"), title: "建议反馈")
            let individualModel3 = IndividualCenterModel(icon: UIImage(named: "shezhi"), title: "设置")
            indeviduals = [individualModel1,individualModel2,individualModel3];

        }else{
            let individualModel1 = IndividualCenterModel(icon: UIImage(named: "wodejifen"), title: "我的积分")
            let individualModel2 = IndividualCenterModel(icon: UIImage(named: "beibaorenguanli"), title: "被保人管理")
            let individualModel3 = IndividualCenterModel(icon: UIImage(named: "fenxiangruanjian"), title: "分享软件")
            let individualModel4 = IndividualCenterModel(icon: UIImage(named: "jianyifankui"), title: "建议反馈")
            let individualModel5 = IndividualCenterModel(icon: UIImage(named: "shezhi"), title: "设置")
            indeviduals = [individualModel1,individualModel2,individualModel3,individualModel4,individualModel5];
        }
    
    }
    
    
    func setupViews() {
        
        centerTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        centerTableView.isScrollEnabled = false
        centerTableView.sectionFooterHeight = 0
        centerTableView.rowHeight = 49
        centerTableView.separatorColor = UIColor(hex: 0xdbdbdb)
//        header.backgroundColor = ConstantColor.appThemeColor
//        centerTableView.tableHeaderView = header
//        header.delegate = self
        centerTableView.backgroundColor = UIColor(hex:0xfcfcfc)
        
        self.header = UINib(nibName: "HDIndividualTopView", bundle: nil).instantiate(withOwner: self, options: nil).last as! HDIndividualTopView
         centerTableView.tableHeaderView = self.header
        self.header.navi = navigationController
        updateUI()
    }
    
    func setUpHeadImageView(){
        self.headImage.layer.masksToBounds = true
        self.headImage.layer.cornerRadius = 34
//        self.header.headImageView.addSubview(self.headImage)
//        self.headImage.snp.makeConstraints({ (make) in
//            make.width.height.equalTo(70)
//            make.centerX.equalTo(self.header.headImageView.snp.centerX)
//            make.centerY.equalTo(self.header.headImageView.snp.centerY)
//        })
        
        
        self.header.HeadImageView.layer.masksToBounds = true
        self.header.HeadImageView.layer.cornerRadius = 50
        
        self.header.userHeadImageView.layer.masksToBounds = true
        self.header.userHeadImageView.layer.cornerRadius = 38
        
        self.header.customUserInfo  = {() -> () in
            self.didEditUserInfo()
        }
    }
    
    func updateUI() {
        if HDAccountHandler.loginType == .notLogin {
            
            self.header.loginView.isHidden = false
            self.header.HeadImageView.isHidden = false
            self.header.userView.isHidden =  true

        } else {
            loadUserInfo()
            
            self.header.loginView.isHidden =  true
            self.header.HeadImageView.isHidden =  true
            self.header.userView.isHidden =  false
            loadUserData()
        }
        
    }
    
    override var preferredStatusBarStyle : UIStatusBarStyle {
        return .default
    }
    
    func loadUserInfo() {
        self.header.nameLabel?.text = HDAccountHandler.userName
        if HDAccountHandler.loginType!.rawValue == 1 {
            self.header.typeLabel?.text = "团体用户"

        }else if HDAccountHandler.loginType!.rawValue == 2 {
                        self.header.typeLabel?.text = "专属用户"
            
        }else if HDAccountHandler.loginType!.rawValue == 3 {
                        self.header.typeLabel?.text = "个人用户"
            
        }
    }
    
    
    //////  分享相关
    func shareApp(){
        UMSocialUIManager.setPreDefinePlatforms([NSNumber(integerLiteral:UMSocialPlatformType.wechatSession.rawValue),NSNumber(integerLiteral:UMSocialPlatformType.wechatTimeLine.rawValue),NSNumber(integerLiteral:UMSocialPlatformType.QQ.rawValue),NSNumber(integerLiteral:UMSocialPlatformType.qzone.rawValue)])
        
        UMSocialUIManager.showShareMenuViewInWindow {[weak self] (platformType, userInfo) in
            
            let messageObject:UMSocialMessageObject = UMSocialMessageObject.init()
            let shareObject:UMShareWebpageObject = UMShareWebpageObject.init()
            shareObject.title = "速赔宝"
            shareObject.descr = "用速度与透明定义理赔"
            shareObject.thumbImage = UIImage.init(named: "shareImage")
            shareObject.webpageUrl = "http://supeibao.huayandan.net/h5/index.html"
            messageObject.shareObject = shareObject;
            UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: self, completion: { (shareResponse, error) in
                
                if error != nil {
                    print("Share Fail")
                }else{
                    print("Share succeed")
                }
            })
        }
        
    }
}
    
//    func didSelectSocialPlatform(_ platformName: String!, with socialData: UMSocialData!) {
//        if platformName == "wxtimeline" {
//            socialData.extConfig.wechatTimelineData.url = "http://supeibao.huayandan.net/h5/index.html"
//            socialData.shareText = "用速度与透明定义理赔"
//        }else if (platformName == "wxsession"){ //微信好友
//
//            socialData.extConfig.wechatSessionData.title = "速赔宝";
//            socialData.extConfig.wechatSessionData.url = "http://supeibao.huayandan.net/h5/index.html";
//
//
//        }else if (platformName == "qq"){ //QQ好友
//
//            socialData.extConfig.qqData.title = "速赔宝";
//            socialData.extConfig.qqData.url = "http://supeibao.huayandan.net/h5/index.html";
//
//        }else{ //QQ空间
//            socialData.extConfig.qzoneData.title = "速赔宝";
//            socialData.extConfig.qzoneData.url = "http://supeibao.huayandan.net/h5/index.html";
//        }
//    }
//}

extension HDIndividualCenterViewController : HDCenterTableHeaderDelegate {
    func didEditUserInfo() {
        if HDAccountHandler.loginType == .notLogin {
//            let registerVC = HDRegistVC()
//            navigationController?.pushViewController(registerVC, animated: true)
            
        } else {
            
            if netJudge.status == .noReachable {
                SVProgressHUD.showError("哦，网络出错了！")
                return
            }else {
                guard let userModel = self.userModel else {
                    return
                }
                
                let individualVC = HDIndividualInformationVC(style: .grouped)
                individualVC.delegate = self
                individualVC.passHeadImg = HDAccountHandler.userHeadImage!
                individualVC.passName = userModel.name
                individualVC.passPhone = userModel.phone
                individualVC.passUserType = userModel.user_type
                individualVC.passCrittype_info = userModel.crittype_info
                individualVC.passCritCode = userModel.critcode
                individualVC.passInsuredgrade =  Int(userModel.insuredgrade!)!
                //显示全部手机号
                individualVC.userInfoModel = userModel
                navigationController?.pushViewController(individualVC, animated: true)
            }
        }
    }
}

extension HDIndividualCenterViewController : UITableViewDataSource {
    
//    func numberOfSections(in tableView: UITableView) -> Int {
//        return 1
//    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if HDAccountHandler.loginType == .notLogin {
           return 3
        }
        return 5
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.accessoryType = .disclosureIndicator
        cell.textLabel?.textColor = CenterColor.centerHomeCellColor
        cell.selectionStyle = .none

        let individualModel = indeviduals[indexPath.row]
        cell.imageView?.image = individualModel.icon
        cell.textLabel?.text = individualModel.title
        
        if HDAccountHandler.loginType == .notLogin {
            self.integralLabel?.removeFromSuperview()
            self.integralLabel = nil
        }else{
            if (indexPath.row == 0){
                if self.integralLabel == nil {
                    self.integralLabel = UILabel()
                    cell.contentView.addSubview(integralLabel!)
                    integralLabel?.font = UIFont.systemFont(ofSize: 14)
                    integralLabel?.textColor =  UIColor.red
                    integralLabel?.textAlignment = .right
                    integralLabel?.snp.makeConstraints { (make) in
                        make.top.equalTo(0)
                        make.left.equalTo(200)
                        make.right.equalTo(0)
                        make.height.equalTo(49)
                    }
                }
                if let integral = integralCount {
                    integralLabel?.text = String(integral)
                }
            }
        }
        return cell
    }
}

extension HDIndividualCenterViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        if indexPath.section == 0 {
//            if indexPath.row == 0 {
//            }else{
//
//
//            }
//        }else if indexPath.section == 1 {
//
//            if indexPath.row == 0 {
//
//
//            }else{
//            }
//        }
        if HDAccountHandler.loginType == .notLogin {
             if indexPath.row == 0 {
                shareApp()
             } else if indexPath.row == 1{
                 navigationController?.pushViewController(HDFeedbackViewController(), animated: true)
             }else if indexPath.row == 2{
                navigationController?.pushViewController(HDSettingViewController(), animated: true)
            }
        }else{
            if indexPath.row == 0 {
                navigationController?.pushViewController(HDintegralVC(), animated: true)
            } else if indexPath.row == 1{
                let recognizee = HDRecognizeeVC()
                recognizee.title = "被保人管理"
                navigationController?.pushViewController(recognizee, animated: true)
            }else if indexPath.row == 2{
                shareApp()
            }else if indexPath.row == 3{
                 navigationController?.pushViewController(HDFeedbackViewController(), animated: true)
            }else if indexPath.row == 4{
                navigationController?.pushViewController(HDSettingViewController(), animated: true)
            }


        }
        
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 15 : 10
    }
}


class HDIndividualTopView: UIView {
    
    @IBOutlet weak var HeadImageView: UIImageView!
    @IBOutlet weak var loginView: UIView!
    
    @IBOutlet weak var userView: UIView!
    @IBOutlet weak var userHeadImageView: UIImageView!
    @IBOutlet weak var balanceLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var typeLabel: UILabel!
    @IBOutlet weak var cashoutBtn: UIButton!
    
    var navi: UINavigationController!
    
    typealias userInfo = () -> ()
    var customUserInfo: userInfo?

    
    override func awakeFromNib() {
        cashoutBtn.layer.borderWidth = 1
        cashoutBtn.layer.cornerRadius = 3
        cashoutBtn.layer.borderColor = UIColor.white.cgColor
    }
    
    
    @IBAction func loginAction(_ sender: UIButton) {
        
        let selectVC = HDIdentitySelectVC()
        selectVC.ToWhere = 0
        
        navi?.pushViewController(selectVC, animated: true)
    }
    
    @IBAction func registAction(_ sender: UIButton) {
        let selectVC = HDIdentitySelectVC()
        selectVC.ToWhere = 1
        
        navi?.pushViewController(selectVC, animated: true)
    }
    
    // 提现
    @IBAction func cashoutAction(_ sender: UIButton) {
//        navi?.pushViewController(HDApplyCashViewController(), animated: true)
        
    }
    
    // 钱包明细
    @IBAction func detailAction(_ sender: UIButton) {
        navi?.pushViewController(HDWalletDetailViewController(), animated: true)
    }
    
    // 用户信息
    @IBAction func userInfoAction(_ sender: UIButton) {
        if(customUserInfo != nil) {
            customUserInfo!()
        }
    }
    
}
